// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { feedApi } from '/api/feed'
import { matchApi } from '/api/match'
import { checkAuth } from '/store/actions'
import { GlobalData } from '/store/state'
import { $event, $logger, $utils } from '/utils'

const defaultInputPlaceholder = '随便说说~'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    feed: {} as DomoFeed,
    topic: {} as DomoTopic,
    comments: [] as DomoComment[],
    navData: [] as DomoFeedCategory[],
    commentFocus: false,
    inputValue: '',
    inputPlaceholder: defaultInputPlaceholder,
    replyUser: 0,
    comment_id: 0, // 一级评论ID
    reply_id: 0, // 被回复评论ID
    postType: '', // '':对评论动态；comment:对评论回复即二级评论，reply:对二级评论回复,发布评论/回复
    /** 键盘弹起高度 */
    keyboardOffsetTop: 0,
    currentIndex: 0,
    limit: 20,
    nomore: false,
    loading: true,
    access: {},
    shareImage: '',
    is_hidden: true,
    share: false,
  },
  async onLoad(Options) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
    })
    // @ts-ignore
    let feedId = Options.feedId ? +Options.feedId : +Options.id
    let from = Options.from
    if (!feedId && Options.scene) {
      const scene = $utils.parseQueryString(Options.scene)
      feedId = scene.feedId ? +scene.feedId : +scene.id
    }
    this.setData({
      from: from,
    })
    try {
      if (!feedId) throw new Error('该赛事不存在或已被删除')
      this.setData({
        loading: false,
      })
      // await this.fetchFeed(feedId)
      // this.fetchComments(feedId)
      // await this.fetchTopics()
      // wx.nextTick(() => {
      //   this.getShareImage()
      // })
    } catch (error) {
      $logger.debug('详情加载失败', { query: Options, error })
      // wx.navigateBack({ delta: 1 })
    }
  },
  async baoming(event: any) {
    console.log(event.currentTarget.dataset.teamid)
    let id = event.currentTarget.dataset.teamid
    if (!id) {
      id = 1
    }
    wx.navigateTo({
      url: `/pages/match/xingjiezhanteam/xingjiezhanteam?id=${id}&from=matchdetail`,
    })
  },
  async onShow() {
    console.log(this.data.currentIndex)
    if (this.data.share) {
      this.setData({
        share: false,
      })
    }
    this.getPosition()
    $event.on('after:boot', this, () => {
      // this.getPosition()
    })
    await checkAuth()
  },
  async onReachBottom() {
    this.fetchComments(this.data.feed.id, true)
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      title: this.data.feed.feed_content || '',
      path: $utils.getSharePath(),
    }
  },
  async changeCurrent(e: any) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    this.updateCurrentTable(index)
  },
  async updateCurrentTable(index: any) {
    this.setData({
      currentIndex: parseInt(index),
    })
  },
  async fetchFeed(feedId: number) {
    try {
      const feed = await feedApi.getFeedDetail(feedId)
      this.setData({ feed })
    } catch (error) {
      const {
        statusCode,
        data: { message },
      } = error
      if (statusCode === 404) {
        wx.showToast({
          title: message,
          icon: 'none',
        })
      }
    }
  },
  async fetchComments(feedId: number, more = true) {
    return
  },
  async fetchTopics() {
    // if (!this.data.feed.topics[0]) return
    // const topic = await topicApi.getTopicDetail(this.data.feed.topics[0].id)
    // this.setData({ topic })
  },
  async viewVideo() {
    await checkAuth()
    if (GlobalData.access.video) {
      wx.navigateTo({
        url: `/pages/feed/video/video?feedId=${this.data.feed.id}`,
      })
    } else {
      // wx.showToast({
      //   title: '小程序暂时无法播放视频呦!',
      //   icon: 'none',
      // })
    }
  },
  async onLike() {
    await checkAuth()
    const feed = this.data.feed
    if (feed.has_liked) {
      feedApi.unlikeFeed(feed.id)
    } else {
      const res = await matchApi.likeFeed(feed.id)
      if (res.amount) {
        $event.emit('showMessage', {
          message: '点赞成功',
          amount: res.amount,
        } as GetRewardMessageReturns)
      }
    }
    this.setData({
      [`feed.has_liked`]: !feed.has_liked,
      [`feed.like_count`]: feed.like_count + (!feed.has_liked ? 1 : -1),
    })
  },
  async onCommentConfirm(event: any) {
    const content: string = event.detail.value
    const { replyUser, comment_id, reply_id, postType } = this.data
    const payload: PostCommentBody = { body: content }
    /*
    对动态进行一级评论参数：body
    对动态的一级评论进行评论(二级评论)参数：body、reply_user(回复用户)、reply_id(一级评论id)、pid(一级评论id)
    对动态的二级评论进行回复(二级评论的回复)参数：body、reply_user(回复用户)、pid(一级评论id)、reply_id(二级评论id)
     */
    if (replyUser) payload.reply_user = replyUser
    if (comment_id) payload.pid = comment_id
    if (reply_id) payload.reply_id = reply_id

    try {
      const { comment, amount } = await matchApi.postFeedComment(this.data.feed.id, payload)
      if (amount) {
        $event.emit('showMessage', {
          message: '评论成功',
          amount: amount,
        } as GetRewardMessageReturns)
      } else {
        wx.showToast({
          title: '评论成功',
          icon: 'success',
          duration: 2000,
        })
      }
      let comments = this.data.comments as any
      if (postType === 'comment' || postType === 'reply') {
        for (let i = 0; i < comments.length; i++) {
          if (comments[i].id === this.data.comment_id) {
            comments[i].replys = [comment, ...comments[i].replys]
            comments[i].reply_count = comments[i].reply_count + 1
            break
          }
        }
      } else {
        comments = [comment, ...this.data.comments]
      }
      this.setData({
        'feed.feed_comment_count': this.data.feed.feed_comment_count + 1,
        comments,
        inputValue: '',
        inputFocus: false,
        replyUser: null as any,
        comment_id: 0,
        reply_id: 0,
        postType: '',
      })
      // $event.emit('showComment', { feedId: +this.data.feed.id })
    } catch (error) {
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }
  },
  async onCommentFocus() {
    await checkAuth()
  },
  bindkeyboardheightchange(event: WechatMiniprogram.TouchEvent) {
    this.handleKeyboard(this, event)
  },
  handleKeyboard: $utils.throttle((that, event: WechatMiniprogram.TouchEvent) => {
    const { height } = event.detail
    if (height != that.data.keyboardOffsetTop) {
      that.setData({
        commentFocus: true,
        keyboardOffsetTop: height,
      })
    }
  }, 100),
  onCommentBlur() {
    this.setData({
      commentFocus: false,
      keyboardOffsetTop: 0,
      inputPlaceholder: defaultInputPlaceholder,
    })
  },
  focusComment() {
    if (this.data.commentFocus) return
    this.setData({ commentFocus: false, replyUser: 0, comment_id: 0, reply_id: 0, postType: '' })
    this.setData({ commentFocus: true })
  },
  onReply(event: WechatMiniprogram.BaseEvent) {
    const { comment = {}, reply = {}, type = '' } = event.currentTarget.dataset
    this.setData({ postType: type || '' })
    const user_id = type === 'reply' ? reply.user_id : comment.user_id
    if (GlobalData.logged!.id === user_id) {
      wx.showActionSheet({
        itemList: ['删除评论'],
        success: async ({ tapIndex }) => {
          if (tapIndex === 0) {
            wx.showLoading({ title: '删除中' })
            try {
              await matchApi.deleteFeedComment(
                comment.commentable_id,
                type === 'reply' ? reply.id : comment.id,
              )

              wx.hideLoading()
              let newList = this.data.comments
              if (this.data.postType === 'reply') {
                for (let i = 0; i < newList.length; i++) {
                  if (newList[i].id === comment.id) {
                    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                    // @ts-ignore
                    newList[i].replys = newList[i].replys.filter(
                      (item: DomoComment) => item.id !== reply.id,
                    )
                    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                    // @ts-ignore
                    newList[i].reply_count = newList[i].reply_count - 1
                    break
                  }
                }
              } else {
                newList = newList.filter((item: DomoComment) => item.id !== comment.id)
              }
              this.setData({
                comments: newList,
                'feed.feed_comment_count': this.data.feed.feed_comment_count - 1,
              })
            } catch (error) {
              this.setData({ postType: '' })
              wx.hideLoading()
              // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
              //@ts-ignore
              wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
            }
          }
        },
      })
    } else {
      this.setData({
        replyUser: type === 'comment' ? comment.user.id : reply.user.id,
        comment_id: comment.id,
        reply_id: type === 'comment' ? comment.id : reply.id,
        inputPlaceholder: `回复 ${type === 'comment' ? comment.user.name : reply.user.name}:`,
        commentFocus: true,
      })
    }
  },
  async onReport(event: WechatMiniprogram.BaseEvent) {
    const { comment = {}, reply = {}, type = '' } = event.currentTarget.dataset
    const user_id = type === 'reply' ? reply.user_id : comment.user_id
    await checkAuth()
    if (GlobalData.logged!.id === user_id) return
    wx.navigateTo({
      url: `/pages/report/report?type=comment&id=${type === 'reply' ? reply.id : comment.id}`,
    })
  },
  async onReportFeed() {
    wx.navigateTo({
      url: `/pages/report/report?type=feed&id=${this.data.feed.id}`,
    })
  },
  onMore() {},
  onDownload() {
    $event.emit('download')
  },
  toProduct() {
    if (this.data.feed.repostable) {
      wx.navigateTo({
        url: `/mall/detail/detail?commodityId=${this.data.feed.repostable.id}`,
      })
    }
  },
  toReply(event: WechatMiniprogram.BaseEvent) {
    const { comment } = event.currentTarget.dataset
    wx.navigateTo({ url: `/pages/feed/reply/reply?id=${comment.id}` })
  },
})
